package com.sinosoft.sinopay.web.util;

import com.sinosoft.sinocloud.platform.common.exception.biz.BizDataErrException;
import com.sinosoft.sinocloud.platform.common.util.SecurityUtil;

import java.util.Map;
import java.util.TreeMap;

/**
 * 【 】
 *
 * @author chenzhiheng
 * @version V1.0
 * @date 16/12/28
 */
public class BatchSignUtil {
    /** 分隔符 */
    private static final String signal ="|";
    /**
     * 微信支付签名方法
     * <p>对传入的数据进行哈希排序,然后通过signal连接符进行拼接后的字符串进行md5加密,返回加密签名信息</p>
     * @param encryMsgs
     * @param signKey
     * @return
     */
    public static String encryMD5(Map<String,String> encryMsgs, String signKey){
        //校验信息完整性
        if(signKey==null || "".equals(signKey.trim()) || encryMsgs==null || encryMsgs.size()<1){
            throw new BizDataErrException("签名信息不完整");
        }

        //首先对非空数据进行排序
        TreeMap<String,String> treeMap = new TreeMap<>();
        for (String tKey : encryMsgs.keySet()) {
            String tValue = encryMsgs.get(tKey);
            if(tValue!=null && !"".equals(tValue)){
                treeMap.put(tKey, encryMsgs.get(tKey));
            }
        }
        //拼接字符串
        StringBuffer sb = new StringBuffer();
        for (String tKey : treeMap.keySet()) {
            sb.append(tKey);
            sb.append("=");
            sb.append(treeMap.get(tKey));
            sb.append(signal);
        }
        String tToEncryStr = sb.toString().substring(0, sb.length()-1);
        //签名
        String md5Check = SecurityUtil.Md5(tToEncryStr+signKey);
        return md5Check;
    }
}
